package cn.hfatec.shms.system.organization.action;


import cn.hfatec.JsonResponse;
import cn.hfatec.constants.SysContant;
import cn.hfatec.freemarker.FreeMarkerUtil;
import cn.hfatec.shms.base.ShmsBaseAction;
import cn.hfatec.shms.cache.CodeInfoCache;
import cn.hfatec.shms.constants.ShmsConstant;
import cn.hfatec.shms.enums.CodeType;
import cn.hfatec.shms.system.organization.model.Organization;
import cn.hfatec.shms.system.organization.model.OrganizationParams;
import cn.hfatec.shms.system.organization.model.OrganizationView;
import cn.hfatec.shms.system.organization.service.OrganizationService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @author hfatec codegen
 * @version 1.0
 *          <p/>
 *          the JAVA code is generate by middlegen
 */
@Controller
@RequestMapping("/system/organization")
public class OrganizationAction extends ShmsBaseAction {

    //服务层
    @Resource(name = "OrganizationService")
    private OrganizationService organizationService;


    /**
     * 查询列表
     */
    @RequestMapping("/list")
    public String list(OrganizationParams organizationParams, Model model) throws InvocationTargetException, IllegalAccessException {

        List<Organization> list = organizationService.queryOrganizationTable(organizationParams);
        List orgList = organizationService.getOrgList(ShmsConstant.ORG_CACHE, list);
        model.addAttribute("organizationsTable", orgList);
        model.addAttribute("isHospitalList", CodeInfoCache.getCodeInfo(CodeType.YES_OR_NO));
        return "/system/organization/list";
    }

    /**
     * 异步查询列表
     */
    @RequestMapping("/ajaxList")
    @ResponseBody
    public String ajaxList(OrganizationParams organizationParams, Model model) {
        try {
            list(organizationParams, model);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/organization/table", model)).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到新增页
     */
    @RequestMapping("/goAdd")
    @ResponseBody
    public String goAdd(String parentOrgId, Integer orgLevel, Model model) {
        try {
            Organization organization = new Organization();
            organization.setParentOrgId(parentOrgId);
            organization.setOrgLevel(orgLevel + 1);
            model.addAttribute("organization", organization);
            model.addAttribute("isHospitalList", CodeInfoCache.getCodeInfo(CodeType.YES_OR_NO));
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/organization/form", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到编辑页
     */
    @RequestMapping("/goEdit")
    @ResponseBody
    public String goEdit(Integer id, Model model) {

        try {
            Organization organization = organizationService.getOrganization(id);
            model.addAttribute("organization", organization);
            model.addAttribute("isHospitalList", CodeInfoCache.getCodeInfo(CodeType.YES_OR_NO));
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/organization/form", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 根据ID删除数据
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String deleteOrganization(Integer id, String orgId) {
        try {
            Organization organization=organizationService.getOrganization(id);
            OrganizationParams organizationParams = new OrganizationParams();
            organizationParams.setParentOrgId(organization.getOrgId());
            List list = organizationService.queryOrganizationTable(organizationParams);
            if (list.size() == 0) {
                organizationService.deleteOrganization(id, orgId);
                return new JsonResponse(JsonResponse.RETURN_SUCCESS, SysContant.DELETE_SUCCESS_MESSAGE).toString();
            } else {
                logger.error("数据" + orgId + "存在子项，请先删除子项！");
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.DELETE_ERROR_MESSAGE).toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据" + id + "删除异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.DELETE_ERROR_MESSAGE).toString();
        }

    }

    /**
     * 保存数据
     */
    @RequestMapping("/save")
    @ResponseBody
    public String saveOrganization(@Valid Organization organization, BindingResult result, Model model) {

        try {
            if (result.hasErrors()) {
                List<ObjectError> errors = result.getAllErrors();
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, errors.get(0).getDefaultMessage()).toString();
            }
            organizationService.saveOrganization(organization);
            model.addAttribute("isHospitalList", CodeInfoCache.getCodeInfo(CodeType.YES_OR_NO));
            model.addAttribute("organization", organizationService.getOrganization(organization.getOrgId()));
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, SysContant.SAVE_SUCCESS_MESSAGE, FreeMarkerUtil.render("/system/organization/form", model)).toString();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据Organization保存异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.SAVE_ERROR_MESSAGE).toString();
        }
    }

    /**
     * 跳转到选择机构页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/goSelectOrg")
    @ResponseBody
    public String goAssignOrg(String orgId, Model model) {

        try {
            List<OrganizationView> list = organizationService.queryAllOrgList();
            model.addAttribute("organizationsTable", list);
            model.addAttribute("orgId", orgId);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/organization/selectOrg", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到选择机构页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/goSelectOrgByAssignOrgId")
    @ResponseBody
    public String goAssignOrgByAssignOrgId(String orgId, Model model) {

        try {
            OrganizationParams organizationParams = new OrganizationParams();
            List<Organization> allOrgList = organizationService.queryOrganizationTable(organizationParams);
            List<OrganizationView> orgList = organizationService.getOrgList(orgId, allOrgList);
            Organization organization = organizationService.getOrganization(orgId);
            OrganizationView organizationView = new OrganizationView();
            BeanUtils.copyProperties(organizationView,organization);
            organizationView.setChildrenOrgList(orgList);
            List<OrganizationView> organizationViews = new ArrayList<OrganizationView>();
            organizationViews.add(organizationView);
            model.addAttribute("orgId", orgId);
            model.addAttribute("organizationsTable", organizationViews);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/organization/selectOrg", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }
}
